from rest_framework import serializers
from .models import Absent,AbsentType,ChoiceAbsentStatus
from apps.oaauth.serializers import UserSerializer
from rest_framework import exceptions
from .uitls import get_responder

class AbsentTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = AbsentType
        fields = "__all__"

class AbsentSerializer(serializers.ModelSerializer):
    # read_only 属性 这个参数，只会在将ORM模型序列化成字典时将这个字段序列化
    # 简单理解就是前端不需要传有这个属性的参数
    # write_only 属性 这个参数，只会将这个data进行校验的时候才会用到
    # 简单理解就是前端需要传入有这个属性的这个字段 因为需要校验这个字段
    absent_type = AbsentTypeSerializer(read_only=True)
    absent_type_id = serializers.IntegerField(write_only=True)
    # 这个发起人 不用前端传 因为这个默认只有登录了才能进行这个操作 前段可以获取到这个
    requester = UserSerializer(read_only=True)
    # 审批者
    responder = UserSerializer(read_only=True)
    class Meta:
        model = Absent
        fields = '__all__'

    # 验证absent_type_id是否在数据库中存在
    def validate_absent_type_id(self,value):
        if not AbsentType.objects.filter(pk=value).exists():
            raise exceptions.ValidationError('考勤类型不存在！')
        return value
    # create
    # 前端传入的数据会在validated_data中
    def create(self, validated_data):
        request = self.context['request']
        user = request.user
        #     获取审批者
        # 如果是部门leader
        # if user.department.leader.uid == user.uid:
        #     # 董事会的leader 请假不需要审批
        #     if user.department.name == '董事会':
        #         responder = None
        #     # 其他部门leader
        #     else:
        #         responder = user.department.manager
        # # 如果不是部门leader
        # else:
        #     responder = user.department.leader
        responder = get_responder(request)

        # 如果是董事会
        if responder is None:
            validated_data['status'] = ChoiceAbsentStatus.PASS
        else:
            validated_data['status'] = ChoiceAbsentStatus.AUDITING
        absent = Absent.objects.create(**validated_data,requester=user,responder=responder)
        return absent
    # update
    def update(self, instance, validated_data):
        # instance 已经找到实例对象 (具体编辑那一条请假)
        if instance.status != ChoiceAbsentStatus.AUDITING:
            raise exceptions.APIException(detail='不能修改已经确定的请假数据！')
        request = self.context['request']
        user = request.user
        if instance.responder.uid != user.uid:
            raise exceptions.APIException(detail='你无权处理该考勤!')
        instance.status = validated_data['status']
        instance.response_content = validated_data['response_content']
        instance.save()
        return instance